package com.ultrapower.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;

import javax.validation.Valid;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.ultrapower.commons.base.BaseController;
import com.ultrapower.commons.result.PageInfo;
import com.ultrapower.commons.shiro.ShiroUser;
import com.ultrapower.commons.utils.JsonUtils;
import com.ultrapower.commons.utils.StringUtils;
import com.ultrapower.model.Allocatedlist;
import com.ultrapower.model.Enterprise;
import com.ultrapower.model.Organization;
import com.ultrapower.model.Product;
import com.ultrapower.model.Task;
import com.ultrapower.model.User;
import com.ultrapower.model.vo.UserVo;
import com.ultrapower.service.IAllocatedlistService;
import com.ultrapower.service.IOrganizationService;
import com.ultrapower.service.IProductService;
import com.ultrapower.service.ITaskService;
import com.ultrapower.service.IUserService;
import com.ultrapower.service.impl.TaskServiceImpl;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sz
 * @since 2018-10-25
 */
@Controller
@RequestMapping("/allocatedlist")
public class AllocatedlistController extends BaseController {

    @Autowired 
    private IAllocatedlistService allocatedlistService;
    @Autowired
    private IOrganizationService orgService;
    @Autowired
    private IUserService userService;
    @Autowired
    private ITaskService taskService; 
    @Autowired
    private IProductService productService;
    
    @GetMapping("/manager")
    public String manager() {
        return "admin/allocatedlist/allocatedlist";
    }
    
    @PostMapping("/dataGrid")
    @ResponseBody
    public PageInfo dataGrid(Integer page, Integer rows, Integer limit, String sort,String order,String orderName,String orderId,String submitTime,String allocateName,String creater,String city,String country) {
    	sort = "id";
    	order = "asc";
        Map<String, Object> condition = new HashMap<String, Object>();
        PageInfo pageInfo = new PageInfo(page, limit, sort, order);
	        if (StringUtils.isNotBlank(orderName)) {
	            condition.put("orderName", orderName);
	        }
	        if (StringUtils.isNotBlank(orderId)) {
	            condition.put("orderId", orderId);
	        }
	        if (StringUtils.isNotBlank(allocateName)) {
	            condition.put("allocateName", allocateName);
	        }
	        if (StringUtils.isNotBlank(creater)) {
	            condition.put("employeeId", creater);
	        }
	        if (StringUtils.isNotBlank(city)) {
	            condition.put("city", city);
	        }
	        if (StringUtils.isNotBlank(country)) {
	            condition.put("country", country);
	        }
	        if (StringUtils.isNotBlank(submitTime)) {
	        	String[] stime = submitTime.split("\\ - ");
	        	String startTime = stime[0].trim();
	        	String endTime = stime[1].trim();
	            condition.put("startTime", startTime);
	            condition.put("endTime", endTime);
	        }
	        ShiroUser shiroUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
	        if(shiroUser.getRoles().contains("admin")) {
	        		        	
	        }else if(shiroUser.getRoles().contains("cm")) {
	        	condition.put("creater", getUserId());
	        }else if(shiroUser.getRoles().contains("sales")) {
	        	condition.put("userId", getUserId());
	        }
        pageInfo.setCondition(condition);
        allocatedlistService.selectDataGrid(pageInfo);
        return pageInfo;
    }
    
    /**
     * 工单列表
     *
     * @param Orderlist
     * @param page
     * @param rows
     * @param sort
     * @param order
     * @return
     */
    @PostMapping("/taskPage")
    @ResponseBody
    public Object taskPage(String companyName, String type, String allocatedId, Integer page, Integer limit, String sort, String order) {
    	sort = "id";
    	order = "asc";
        Map<String, Object> condition = new HashMap<String, Object>();
        PageInfo pageInfo = new PageInfo(page, limit, sort, order);
        ShiroUser shiroUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
	        if(shiroUser.getRoles().contains("sales")) {
	        	condition.put("userId", getUserId());
	        }
	        if (StringUtils.isNotBlank(allocatedId)) {
	            condition.put("allocatedId", allocatedId);
	        }
	        if (StringUtils.isNotBlank(companyName)) {
	            condition.put("companyName", companyName);
	        }
	        type = taskService.selectTypeByOrderId(null,allocatedId);
	        condition.put("type", type);
        pageInfo.setCondition(condition);
        allocatedlistService.selectTaskPage(pageInfo);
        return pageInfo;
    }
    
    /**
     * 添加页面
     * @return
     */
    @GetMapping("/addPage")
    public String addPage() {
        return "admin/allocatedlist/allocatedlistAdd";
    }
    
    /**
     * 添加
     * @param 
     * @return
     */
    @PostMapping("/add")
    @ResponseBody
    public Object add(@Valid Allocatedlist allocatedlist) {
        allocatedlist.setCreateTime(new Date());
        allocatedlist.setUpdateTime(new Date());
        allocatedlist.setDeleteFlag(0);
        boolean b = allocatedlistService.insert(allocatedlist);
        if (b) {
            return renderSuccess("添加成功！");
        } else {
            return renderError("添加失败！");
        }
    }
    
    /**
     * 添加
     * @param 
     * @return
     */
//    @SuppressWarnings("unchecked")
	@PostMapping("/addBatch")
    @ResponseBody
    public Object addBatch(Enterprise enterprise, String tasks, String users, String way, String orderId,String isAll) {
    	System.out.println(isAll);
    	SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
    	Allocatedlist allocatedlist = new Allocatedlist();
    	allocatedlist.setName(format.format(new Date())+"批次");
    	allocatedlist.setCreater(getUserId());
    	allocatedlist.setOrderId(orderId);
    	allocatedlist.setCreateTime(new Date());
    	allocatedlistService.insert(allocatedlist);
    	
    	List taskList = new ArrayList<>();
    	if(isAll!=null&&isAll.equals("true")) {
    		 Map<String, Object> condition = new HashMap<String, Object>();

	        User user = userService.selectById(getUserId());
	    	Organization oi = orgService.selectById(user.getOrganizationId());
	    	
	    	condition.put("province", oi.getProvince());
	    	
	    	condition.put("cityName", oi.getCity());
	    			
	        if (StringUtils.isNotBlank(orderId)) {
	            condition.put("orderId", orderId);
	        }
	        if (StringUtils.isNotBlank(enterprise.getIndustry())) {
	            condition.put("industry", enterprise.getIndustry());
	        }
	        if (StringUtils.isNotBlank(enterprise.getDevelop()) && !"0".equals(enterprise.getDevelop())) {
	            condition.put("develop", enterprise.getDevelop());
	        }
	        if (StringUtils.isNotBlank(enterprise.getCompanyName())) {
	            condition.put("companyName", enterprise.getCompanyName());
	        }
	        if (StringUtils.isNotBlank(enterprise.getType())) {
	            condition.put("type", enterprise.getType());
	        }
	        String ent_type = taskService.selectTypeByOrderId(orderId,null);
	        condition.put("ent_type", ent_type);
	        
	        if (StringUtils.isNotBlank(enterprise.getScale())) {
	            condition.put("scale", enterprise.getScale());
	        }
	        taskList = allocatedlistService.selectOrderTaskId(condition);
    	}else {
    		taskList = JsonUtils.parse(tasks, List.class);
    	}
    	users = StringEscapeUtils.unescapeHtml(users);

    	PageInfo pageInfo = new PageInfo();
    	userService.selectAllMember(pageInfo);
    	List<Map> userList = pageInfo.getData();
    	Random ra =new Random(); 
    	List<Task> updateTasks = new ArrayList<>();
    	if(way.equals("hm")) {
        	Map<String, String> usermap = new HashMap<>();
        	usermap = JsonUtils.parse(users, HashMap.class);
        	int t = 0;
        	for (Map.Entry<String, String> entry : usermap.entrySet()) {
        		for(int i=0;i<Integer.parseInt(entry.getValue());i++){
        			Task task = new Task();
                	task.setId((int)taskList.get(t));
                	task.setAllocateId(allocatedlist.getId());
                	task.setUserId(Long.parseLong(entry.getKey()));
                	updateTasks.add(task);
                	t++;
        		}
        		}
    	}else {
        for(int i=0;i<taskList.size();i++) {
        	Task task = new Task();
        	Long userId = (Long)userList.get(ra.nextInt(userList.size())).get("id");
        	task.setId((int)taskList.get(i));
        	task.setAllocateId(allocatedlist.getId());
        	task.setUserId(userId);
        	updateTasks.add(task);
        }
    	}
        Boolean b =  taskService.updateBatchById(updateTasks);
        if (b) {
            return renderSuccess("添加成功！");
        } else {
            return renderError("添加失败！");
        }
    }
    
    /**
     * 删除
     * @param id
     * @return
     */
    @PostMapping("/delete")
    @ResponseBody
    public Object delete(Long id) {
        Allocatedlist allocatedlist = new Allocatedlist();
        allocatedlist.setId(id);
        allocatedlist.setUpdateTime(new Date());
        allocatedlist.setDeleteFlag(1);
        boolean b = allocatedlistService.updateById(allocatedlist);
        if (b) {
            return renderSuccess("删除成功！");
        } else {
            return renderError("删除失败！");
        }
    }
    
    /**
     * 编辑
     * @param model
     * @param id
     * @return
     */
    @GetMapping("/editPage")
    public String editPage(Model model, Long id) {
        Allocatedlist allocatedlist = allocatedlistService.selectById(id);
        model.addAttribute("allocatedlist", allocatedlist);
        return "admin/allocatedlist/allocatedlistEdit";
    }
    
    /**
     * 编辑
     * @param 
     * @return
     */
    @PostMapping("/edit")
    @ResponseBody
    public Object edit(@Valid Allocatedlist allocatedlist) {
        allocatedlist.setUpdateTime(new Date());
        boolean b = allocatedlistService.updateById(allocatedlist);
        if (b) {
            return renderSuccess("编辑成功！");
        } else {
            return renderError("编辑失败！");
        }
    }
    
    /**
     * 分享产品页
     *
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/sharePage")
    public String sharePage(Model model, String allocatedId, String id) {
    	int productId;
    	if(id==null||id.equals("")) {
    		productId = allocatedlistService.selectproductByAid(allocatedId);
    	}else{
    		productId = Integer.parseInt(id);
    	}
    	Product product = productService.selectProById(productId);
        model.addAttribute("product", product);
        return "admin/product/productShare";
    }
    
    /**
     * 订单列表——任务列表
     *
     * @return
     */
    @GetMapping("/taskDetails")
    public String taskDtails() {
        return "admin/allocatedlist/taskDetails";
    }

    
    @PostMapping("/enterpriseGrid")
    @ResponseBody
    public PageInfo enterpriseGrid(Enterprise enterprise, String orderId,Integer page, Integer limit, String sort, String order, String cityName,String industry,String companyName,String develop,String type,String scale) {
    	sort = "id";
    	order = "asc";
        PageInfo pageInfo = new PageInfo(page, limit, sort, order);
        Map<String, Object> condition = new HashMap<String, Object>();

        User user = userService.selectById(getUserId());
    	Organization oi = orgService.selectById(user.getOrganizationId());
    	
    	condition.put("province", oi.getProvince());
    	
    	condition.put("cityName", oi.getCity());
    			
        if (StringUtils.isNotBlank(orderId)) {
            condition.put("orderId", orderId);
        }
        if (StringUtils.isNotBlank(industry)) {
            condition.put("industry", industry);
        }
        if (StringUtils.isNotBlank(develop) && !"".equals(develop)) {
            condition.put("develop", develop);
        }
        if (StringUtils.isNotBlank(companyName)) {
            condition.put("companyName", companyName);
        }
        if (StringUtils.isNotBlank(industry)) {
            condition.put("industry", industry);
        }
        if (StringUtils.isNotBlank(type)) {
            condition.put("type", type);
        }
        String ent_type = taskService.selectTypeByOrderId(orderId,null);
        condition.put("ent_type", ent_type);
        
        if (StringUtils.isNotBlank(scale)) {
            condition.put("scale", scale);
        }
        pageInfo.setCondition(condition);
        allocatedlistService.selectOrderEnterprise(pageInfo);
        return pageInfo;
    }
}
